from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
x,y=load_iris().data[:,2:4],load_iris().target
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0,test_size=50)
depth=np.arange(1,15)
err_list=[]
for i in depth:
    model=DecisionTreeClassifier(criterion='entropy',max_depth=i)
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    err=1-ac
    err_list.append(err)
plt.plot(depth,err_list,'ro-')
plt.rcParams['font.sans-serif']='Simhei'
plt.xlabel('决策树深度')
plt.ylabel('预测误差率')
plt.show()
model=DecisionTreeClassifier(criterion='entropy',max_depth=3)
model.fit(x_train,y_train)
pred=model.predict(x_test)
ac=accuracy_score(y_test,pred)
print('模型的预测准确率为：\n',ac)
from matplotlib.colors import ListedColormap
N,M=500,500
t1=np.linspace(0,8,N)
t2=np.linspace(0,3,M)
x1,x2=np.meshgrid(t1,t2)
x_new=np.stack((x1.flat,x2.flat),axis=1)
y_predict=model.predict(x_new)
y_hat=y_predict.reshape(x1.shape)
iris_cmap=ListedColormap(["#ACC6C0","#FF8080","#A0A0FF"])
plt.pcolormesh(x1,x2,y_hat,cmap=iris_cmap)
plt.scatter(x[y==0,0],x[y==0,1],c='r',s=60,marker='o')
plt.scatter(x[y==1,0],x[y==1,1],c='b',s=60,marker='s')
plt.scatter(x[y==2,0],x[y==2,1],c='g',s=60,marker='v')
plt.rcParams['font.sans-serif']='Simhei'
plt.xlabel('花瓣长度')
plt.ylabel('花瓣宽度')
plt.show()